package com.lemurian.bankdata.action.business;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.lemurian.bankdata.dto.DelegasiPengetikanDTO;
import com.lemurian.bankdata.dto.LogHelper;
import com.lemurian.bankdata.lite.authentication.BankDataPrincipal;
import com.lemurian.bankdata.lite.enums.UserActivityType;
import com.lemurian.bankdata.lite.enums.UserType;
import com.lemurian.bankdata.lite.logger.BankDataLogger;
import com.lemurian.bankdata.lite.struts.Pager;
import com.lemurian.bankdata.lite.struts.PartialList;
import com.lemurian.bankdata.lite.utils.GeneralConstant;
import com.lemurian.bankdata.services.ActivityLogService;
import com.lemurian.bankdata.services.ClientService;
import com.lemurian.bankdata.services.UserService;
import com.lemurian.bankdata.utils.BaseAction;
import com.lemurian.entity.Client;
import com.lemurian.entity.User;
import com.opensymphony.xwork2.Preparable;

public class DelegasiPengetikanAction extends BaseAction implements Preparable {

	private static final long serialVersionUID = 1L;

	private BankDataLogger log = BankDataLogger.getLogger(DelegasiPengetikanAction.class.getSimpleName());
	
	private List<Client> clients = new ArrayList<Client>();
	
	private List<User> listPetugasKetik;
	private List<DelegasiPengetikanDTO> listId;
	
	private String nama = "", noSertifikat = "";
	
	private User user;
	private BankDataPrincipal principal;
	
	@Autowired
	private ClientService clientService;
	@Autowired
	private UserService userService;
	
	@Autowired 
	private ActivityLogService userActivityLogService;
	private LogHelper userActivityLog;
	
	@Override
	public void prepare() throws Exception {
		log.info(": : : : : ON DELEGASI PENGETIKAN ");
		
		principal = (BankDataPrincipal) getSession().get(GeneralConstant.USER_PRINCIPAL);
		user = principal.getUser();
	}
	
	@Override
	public String list() {
		setPreviousPage(GeneralConstant.LIST);
		
		try {
			listPetugasKetik = userService.getUserByUserType(UserType.LETTER_TYPIS.id());
			
			/* LIST CERTIFICATE */
			Criterion criterion = null;
			
			log.info(": : : : : USER TYPE ID "+user.getUserType().getId());
			if(user.getUserType().getId() == UserType.ADMINISTRATOR.id()) {
				criterion = Restrictions.ne("id", new Integer(-1));
			} else {
				criterion = Restrictions.eq("department.id", user.getDepartment().getId());
			}
			
			PartialList<Client> partialList = clientService.findByCriteria(getStart(), getCount(), getAscDesc().equalsIgnoreCase("desc") ? Order.desc(getOrderBy().length() > 0 ? getOrderBy() : "id") : Order.asc(getOrderBy().length() > 0 ? getOrderBy() : "id"),
					nama.length() > 0 ? Restrictions.ilike("debitur.name", nama, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1)),
					//noSertifikat.length() > 0 ? Restrictions.ilike("certificate.lemurian", noSertifikat, MatchMode.ANYWHERE) : Restrictions.ne("id", new Integer(-1)),
					criterion);
			
			clients = partialList.getList();
			
			setPager(Pager.generatePager(getStart(), getCount(), partialList.getTotal()));
            setPagerItem(Pager.generatePagerItem(getStart(), getCount(), partialList.getTotal()));

            partialList = null;
			
		} catch (Throwable t) {
			t.printStackTrace();
		}
		
		setMappedRequest(GeneralConstant.LIST);
        return SUCCESS;
	}
	
	@Override
	public String save() {
		
		Client client = null;
		User officerType = null;
		
		if(listId != null && listId.size() > 0) {
			for(DelegasiPengetikanDTO dp : listId) {
				
				if(dp.getClientId() > 0 && dp.getOfficerTypeId() > 0) {
					
					log.sInfo(": : : : CLIENT  ID [%s]", dp.getClientId());
					
					client = clientService.load(dp.getClientId());
					
					log.sInfo(": : : : OFFCIER ID [%s]", dp.getOfficerTypeId());
					
					officerType = userService.load(dp.getOfficerTypeId());
					
					if(client != null && officerType != null) {
							
						userActivityLog = new LogHelper(user, UserActivityType.DELEGATE_LETTER_TYPIS);
						
			            try {
			            	client.setOfficerType(officerType);
							clientService.save(client);
			            	
			                log.sInfo(" :: User [%s:%s] is successfully delegate certificate [%s] to letter typis [%s]", user.getId(), user.getName(), client.getDebitur().getName(), officerType.getName());

			                //check if activity is success
			                userActivityLog.setStatus(LogHelper.SUCCESS_ACTIVITY);
			            } catch (Exception e) {
			                log.sInfo(" :: Error was raised when User [%s:%s] delegate certificate [%s] to letter typis [%s]", user.getId(), user.getName(), client.getDebitur().getName(), officerType.getName());
			                
			                //set activity log status into failed
			                userActivityLog.setStatus(LogHelper.FAILED_ACTIVITY);
			                userActivityLog.setErrorMsg(e.getMessage());
			            }
			            //save activity log
			            userActivityLog.setSessionId(ServletActionContext.getRequest().getSession().getId());
			            userActivityLog.getAdditionalParams().add(client.getDebitur().getName());
			            userActivityLog.getAdditionalParams().add(officerType.getName());
			            userActivityLogService.saveUserActivity(userActivityLog);
					} else {
						continue;
					}
					
				}
				
			}
			
			addCustomActionMessage("Successfully delegate officer type");
		} else {
			addCustomActionError("Failed delegate officer type");
		}
		
		setMappedRequestFullPath("/DelegasiPengetikanAction_list.do");
		return GeneralConstant.REDIRECT;
	}
	
	@Override
	public String add() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String delete() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String detail() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String edit() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String update() {
		// TODO Auto-generated method stub
		return null;
	}

	public List<Client> getClients() {
		return clients;
	}

	public void setClients(List<Client> clients) {
		this.clients = clients;
	}

	public String getNama() {
		return nama;
	}

	public void setNama(String nama) {
		this.nama = nama;
	}

	public String getNoSertifikat() {
		return noSertifikat;
	}

	public void setNoSertifikat(String noSertifikat) {
		this.noSertifikat = noSertifikat;
	}

	public List<User> getListPetugasKetik() {
		return listPetugasKetik;
	}

	public void setListPetugasKetik(List<User> listPetugasKetik) {
		this.listPetugasKetik = listPetugasKetik;
	}

	public List<DelegasiPengetikanDTO> getListId() {
		return listId;
	}

	public void setListId(List<DelegasiPengetikanDTO> listId) {
		this.listId = listId;
	}
	
}